<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/10/27
 * Time: 10:29
 */

namespace Api\Controller;


class InvestController extends BeforController
{
    /**
     * 资金历史纪录
     */
    public function history()
    {
        $uid = I('userId',$this->_userinfo['muid'],'intval');
        $uid = empty($uid)?$this->_userinfo['muid']:$uid;
        $lists = M('StockPosition')->field(['code','sid'])->where(['muid'=>$uid,'ctime'=>['GT',0]])->select();
        if(empty($lists)){
            $this->response(['code'=>__LINE__,'msg'=>'暂无历史纪录'],'json');
        }
        $code = [];
        $sid=[];
        foreach($lists as $k=>$val){
            $code[$val['code']]=$val['code'];
            $sid[$val['sid']]=$val['sid'];
        }
        $logs=M('StockTradesLog');
        $buy = $logs->field(['spid','sum(price*total) as buy'])->where(['type'=>0,'spid'=>['in',$sid]])->group('spid')->select();
        $sell = $logs->field(['spid','sum(price*total) as sell'])->where(['type'=>1,'spid'=>['in',$sid]])->group('spid')->select();
        foreach($buy as $k=>$val){
            unset($buy[$k]);
            $buy[$val['spid']]=$val['buy'];
        }

        foreach($sell as $k=>$val){
            unset($sell[$k]);
            $sell[$val['spid']]=$val['buy'];
        }
        $codename = M('Stock')->field(['code','name'])->where(['code'=>['in',$code],'type'=>['in',[0,1,2,3,4,5,15,16]]])->select();
        foreach($codename as $k=>$v){
            unset($codename[$k]);
            $codename[$v['code']]=$v['name'];
        }

        foreach($lists as $k=>$val){
            $val['name']=$codename[$val['code']];
            $val['totalBuy']=$buy[$val['sid']];
            $val['totalSell']=$sell[$val['sid']];
            $val['totalBreakeven']=$val['totalSell']-$val['totalBuy'];
            $val['rate']=number_format($val['totalBreakeven']/$val['totalBuy']*100,2,'.','').'%';
            $lists[$k]=$val;
        }
        $this->response(['code' => 0, 'data' => ['list'=>$lists]], 'json');
    }

    public function info()
    {
        $uid = I('userId',$this->_userinfo['muid'],'intval');
        $uid = empty($uid)?$this->_userinfo['muid']:$uid;
        $info = M('Member')->field(['bankroll','avatrade','avadays','winrate','income'])->join('__MEMBER_COUNT__ on __MEMBER_COUNT__.mid=__MEMBER__.muid','LEFT')->where(['muid'=>$uid])->find();
        $logs=M('StockTradesLog');
        // 持仓记录
        $dbpostion = M('StockPosition');
        // 获取持仓股票
        $potion=$dbpostion->field(['code','sid','total'])->where(['muid'=>$uid,'ctime'=>0])->select();
        $codes=[];
        foreach($potion as $k=>$v){
            unset($potion[$k]);
            $potion[$v['sid']]=$v;
            $codes[$v['code']]=$v['code'];
        }
        // 获取单位成本
        $avaCost = $logs->field(['sum(price*total)/sum(total) as avaCost','spid'])->where(['muid'=>$uid,'type'=>0,'spid'=>['in',array_keys($potion)]])->group('spid')->select();
        foreach($avaCost as $k=>$v){
            unset($avaCost[$k]);
            $avaCost[$v['spid']]=intval(floatval($v['avaCost'])*100)/100;
        }
        // 获取持仓已经售卖的数量的收益和成本以及总量
        $sell_lists=$logs->field(['spid','sum((price-present)*total) as payoff','sum(present*total) as cost','sum(total) as total'])->where(['muid'=>$uid,'type'=>1,'spid'=>['in',array_keys($potion)]])->group('spid')->select();
        foreach($sell_lists as $k=>$v){
            unset($sell_lists[$k]);
            $sell_lists[$v['spid']]=$v;
        }
        $codename = M('Stock')->field(['name','code','type'])->where(['code'=>['in',$codes],'type'=>['in',[0,1,2,3,4,5,15,16]]])->select();
        $newcode = [];
        foreach($codename as $k=>$v){
            unset($codename[$k]);
            if (in_array($v['type'], [0, 1, 2])) {
                $newcode[$v['code']] = 'sh' . $v['code'];
                $codename[$v['code']]=$v;
            } elseif (in_array($v['type'], [3, 4, 5,15,16])) {
                $newcode[$v['code']] = 'sz' . $v['code'];
                $codename[$v['code']]=$v;
            }
        }
        import('Common.Util.Stock');
        $stock              = new \Stock();
        $data               = $stock->GetQuote($newcode);
        // 获取售卖的总收益
        $payoff=$logs->field(['sum((price-present)*total) as payoff','sum(present*total) as cost'])->where(['muid'=>$uid,'type'=>1])->find();
        // 计算持仓股票收益
        $position_gain = 0;
        $totalFunds = 0;
        $potion_total=0;
        foreach($potion as $k=>$v){
            $potion_total+=$v['total'];
            $position_gain+= ($data[$v['code']][3]-$avaCost[$v['sid']])*$v['total'];
            $totalFunds+=$data[$v['code']][3]*$v['total'];
        }
        $lists = [
            'avaFunds'     => $info['bankroll'],
            'avaStocks'    => empty(count($data))?0:$potion_total/count($data),
            'avaTrade'     => $logs->where(['muid'=>$uid])->count(),
            'breakeven'    => number_format($position_gain,2,'.',''),
            'cangWei'      => number_format($totalFunds/($totalFunds+$info['bankroll']),4,'.',''),
            'lastTrade'    => date('Y-m-d H:i:s',$logs->where(['muid'=>$uid])->max('trtime')),
            'netValue'     => number_format($totalFunds,2,'.',''),
            'orginalTrade' => date('Y-m-d H:i:s',$logs->where(['muid'=>$uid,'trtime'=>['GT',0]])->min('trtime')),
            'ranking'      => $uid,
            'rateOfMonth'  => $payoff['payoff']+$position_gain,
            'rateOfWin'    => empty($info['winrate'])?0:$info['winrate'],
            'totalFunds'   => $totalFunds+$info['bankroll'],
            'totalIncome'  => $payoff['payoff']+$position_gain
        ];
        $this->response(['code' => 0, 'data' => $lists], 'json');
    }

    public function position()
    {
        $uid = I('userId',$this->_userinfo['muid'],'intval');
        $uid = empty($uid)?$this->_userinfo['muid']:$uid;
        // 持仓记录
        $lists = M('StockPosition')->field(['code','sid','total'])->where(['muid'=>$uid,'ctime'=>0])->select();
        $pids=[];
        $codes=[];
        foreach($lists as $v){
            $pids[$v['sid']]=$v['sid'];
            $codes[$v['code']]=$v['code'];
        }
        // 查找买入记录
        $dblog = M('StockTradesLog');
        // 获取平均交易成本
        $avaCost = $dblog->field(['sum(price*total)/sum(total) as avaCost','spid'])->where(['muid'=>$uid,'type'=>0,'spid'=>['in',$pids]])->group('spid')->select();
        foreach($avaCost as $k=>$v){
            unset($avaCost[$k]);
            $avaCost[$v['spid']]=intval(floatval($v['avaCost'])*100)/100;
        }
        // 获取已经卖出的数量 以及卖出的收益
        $sell_lists=$dblog->field(['spid','sum((price-present)*total) as payoff','sum(present*total) as cost','sum(total) as total'])->where(['muid'=>$uid,'type'=>1,'spid'=>['in',$pids]])->group('spid')->select();
        if(!empty($sell_lists)){
	foreach($sell_lists as $k=>$v){
            unset($sell_lists[$k]);
            $sell_lists[$v['spid']]=$v;
        }}else{
		$sell_lists=[];
	}
        // 不可卖数量
        $not_sell = $dblog->field(['sum(total) as total','spid'])->where(['muid'=>$uid,'type'=>0,'spid'=>['in',$pids],'trtime'=>['between',[strtotime(date('Y-m-d')),strtotime(date('Y-m-d 23:59:59'))]]])->group('spid')->select();
        if(!empty($not_sell)){
	foreach($not_sell as $k=>$v){
            unset($not_sell[$k]);
            $not_sell[$v['spid']]=$v['total'];
        }}else{
		$not_sell=[];
	}
        // 查询股票名称
        $codename = M('Stock')->field(['name','code','type'])->where(['code'=>['in',$codes],'type'=>['in',[0,1,2,3,4,5,15,16]]])->select();
        $newcode = [];
        foreach($codename as $k=>$v){
            unset($codename[$k]);
            if (in_array($v['type'], [0, 1, 2])) {
                $newcode[$v['code']] = 'sh' . $v['code'];
                $codename[$v['code']]=$v;
            } elseif (in_array($v['type'], [3, 4, 5,15,16])) {
                $newcode[$v['code']] = 'sz' . $v['code'];
                $codename[$v['code']]=$v;
            }
        }
        import('Common.Util.Stock');
        $stock              = new \Stock();
        $data               = $stock->GetQuote($newcode);
        foreach($lists as $k=>$v){
            $value=['avaCost'=>$avaCost[$v['sid']],'code'=>$v['code']];
            $value['name']=$data[$v['code']][0];
            $value['sid']=$v['sid'];
            // 现价
            $value['currentPrice']=$data[$v['code']][3];
            $value['stocksAmount']=$v['total'];
            $value['sellAmount']=$value['stocksAmount']-(empty($not_sell[$v['sid']])?0:intval($not_sell[$v['sid']]));
            $value['lastValue']=$value['stocksAmount']*$value['currentPrice'];
            $value['rate']=$value['lastValue']-$value['avaCost']*$value['stocksAmount']+(empty($sell_lists[$v['sid']]['payoff'])?0:$sell_lists[$v['sid']]['payoff']);
            $value['rate']=$value['rate']/($value['avaCost']*$value['stocksAmount']+(empty($sell_lists[$v['sid']]['cost'])?0:$sell_lists[$v['sid']]['cost']));
            $value['rate']=number_format($value['rate']*100,2,'.','').'%';
            $value['avaCost']=number_format($value['avaCost'],2,'.','');
            $lists[$k]=$value;
        }
        $this->response(['code' => 0, 'data' => ['list'=>$lists]], 'json');
    }

    /**
     * 交易日志
     */
    public function rawlogs(){
        $sid = I('post.sid','','trim');
        $showCount = I('post.showCount', 15, 'intval');
        $pageCount = I('post.pageCount', 1, 'intval');
        $pageCount = max($pageCount, 1);
        $dbpostion = M('StockPosition');
        // 查找买入记录
        $dblog = M('StockTradesLog');
        $dbinfo = $dbpostion->where(['sid'=>$sid])->find();
        if(empty($dbinfo)){
            $this->response(['code'=>__LINE__,'msg'=>'交易记录不存在'],'json');
        }
        $codename = M('Stock')->field(['name','code','type'])->where(['code'=>$dbinfo['code'],'type'=>['in',[0,1,2,3,4,5,15,16]]])->find();
        if (in_array($codename['type'], [0, 1, 2])) {
            $newcode = 'sh' . $codename['code'];
        } elseif (in_array($codename['type'], [3, 4, 5,15,16])) {
            $newcode = 'sz' . $codename['code'];
        }
        import('Common.Util.Stock');
        $stock              = new \Stock();
        $data               = $stock->GetQuote($newcode);
        $resinfo=['deadline'=>empty($dbinfo['ctime'])?(((strtotime(date('Y-m-d'))-strtotime(date('Y-m-d',$dbinfo['atime'])))/86400)+1):(((strtotime(date('Y-m-d',$dbinfo['ctime']))-strtotime(date('Y-m-d',$dbinfo['atime'])))/86400)+1)];
        $resinfo['sellDate']=empty($dbinfo['ctime'])?'':date('Y-m-d H:i:s',$dbinfo['ctime']);
        $sell = $dblog->field('sum(total) as totals','sum(present*total) as cost','sum(present*total)/sum(total) as avacost')->where(['spid'=>$sid,'type'=>1,'trtime'=>['GT',0]])->find();
        $buy = $dblog->field('sum(total) as totals','sum(present*total) as cost','sum(present*total)/sum(total) as avacost')->where(['spid'=>$sid,'type'=>0,'trtime'=>['GT',0]])->find();
        $resinfo['avaCost']=empty($buy['avacost'])?0:$buy['avacost'];
        $resinfo['totalBuy']=empty($buy['cost'])?0:$buy['cost'];
        $resinfo['totalTradeAmount']=(empty($buy['totals'])?0:intval($buy['totals']))+(empty($sell['totals'])?0:intval($sell['totals']));
        $resinfo['totalSell']=empty($sell['cost'])?'':$sell['cost'];
        $resinfo['avaPrice']=empty($sell['avacost'])?'':$sell['avacost'];
        $resinfo['totalDefault']=empty($resinfo['totalSell'])?0:($resinfo['totalSell']-$resinfo['totalBuy']);
        $resinfo['totalRate']=empty($resinfo['totalSell'])?0:(number_format($resinfo['totalDefault']/$resinfo['totalBuy']*100,2,'.','').'%');
        $resinfo['name']=$data[$dbinfo['code']][0];
        $resinfo['newPrice']=$data[$dbinfo['code']][3];
        $resinfo['rate']=number_format(($data[$dbinfo['code']][3]-$data[$dbinfo['code']][1])/$data[$dbinfo['code']][1]*100,'2','.','').'%';
        $lists = $dblog->field(['trtime as date','total as amount','price','cost as fee','(total*price) as money','addtime','type'])->where(['spid'=>$sid])->order('trtime desc')->limit((($pageCount - 1) * $showCount) . ',' . $showCount)->select();
        foreach($lists as $k=>$val){
            $val['depute']=empty($val['date'])?1:0;
            $val['date']=empty($val['date'])?date('Y-m-d H:i:s',$val['addtime']):date('Y-m-d H:i:s',$val['date']);
            unset($val['addtime']);
            $lists[$k]=$val;
        }
        $resinfo['list']=$lists;
        $resinfo['totalPage']=$dblog->where(['spid'=>$sid])->count();

        $this->response(['code'=>0,'data'=>$resinfo,'msg'=>'ok'],'json');
    }
}
